#include "Fragment_LinkLayer.h"
#include "Fragment_TransportLayer.h"
#include "stdio.h"
#include "stdint.h"



void hex_dump(const char* label, const void* data, size_t len)
{
    if (data == NULL) {
        printf("%s: NULL pointer\n", label ? label : "HexDump");
        return;
    }

    const uint8_t* buf = (const uint8_t*)data;
    size_t i, j;

    if (label) printf("%s:\n", label);

    for (i = 0; i < len; i += 32) {
        // 打印偏移地址
        printf("  %04zx  ", i);

        // 打印16字节的16进制数据
        for (j = 0; j < 32; ++j) {
            if (i + j < len)
                printf("%02X ", buf[i + j]);
            else
                printf("   ");  // 对齐
        }

        printf(" ");

        // 打印ASCII字符
        for (j = 0; j < 32; ++j) {
            if (i + j < len) {
                char c = buf[i + j];
                printf("%c", isprint(c) ? c : '.');
            } else {
                printf(" ");
            }
        }

        printf("\n");
    }
}

void AppProtocol_SendCallback(uint8_t* data, uint16_t length)
{
    // hex_dump("AppProtocol_send", data, length);
    Fragment_Received(data, length);
}

void AppProtocol_RecvCmpCallback(uint8_t* data, uint16_t length)
{
    // hex_dump("AppProtocol_RecvCmpCallback", data, length);

    static uint16_t pre_index = 0;
    if (length == pre_index + 1) {
        printf(" index: %d OK \r\n", length);
    } else {
        printf(" ##################################### error index: %d \r\n", length);
    }
    pre_index = length;
}

int main(int argc, char const *argv[])
{
    /* code */

    // xInPayload.len = 2;
    // xInPayload.data[0] = 0x01;
    // xInPayload.data[1] = 0x03;
    uint8_t data[256] = {0};
    uint16_t length = 0;

    // length = Fragment_Frame_Serialize(&xInPayload, data, sizeof(data));
    // hex_dump("parser In", &data[0], length);

    // Fragment_Frame_Parse(data, length, &xOutPayload);
    // hex_dump("parser output", &xOutPayload.data[0], xOutPayload.len);

    
    // printf("Serialized length: %d\n", length);
    Fragment_TransportInit(AppProtocol_SendCallback, AppProtocol_RecvCmpCallback);
    for (uint16_t k = 1; k < 129; k++) {
        /* code */

        uint8_t arrBigData[k];
        for (int i = 0; i < sizeof(arrBigData); ++i) {
            arrBigData[i] = i % 256;  // 填充数据
        }
        

        printf("Data Total length: %d \r\n", k);
        Fragment_Transmitter(arrBigData, k);
        // hex_dump("Transmitted Data", arrBigData, k);

        // Fragment_Received(arrBigData, k);

    }
    return 0;
}

